package main

import (
	"context"
	"fmt"
	"review-service/internal/data/mysqlquery"
	"review-service/internal/model/mysqlmodel"

	"gorm.io/driver/mysql"
	"gorm.io/gen"
	"gorm.io/gorm"
)

func autoMigrae(db *gorm.DB) {
	// Migrate the schema
	if err := db.AutoMigrate(&mysqlmodel.ReviewInfo{}, &mysqlmodel.ReviewImage{}, &mysqlmodel.ReviewReployInfo{}); err != nil {
		panic(err)
	}
	g := gen.NewGenerator(gen.Config{
		OutPath: "../data/mysqlquery",
		Mode:    gen.WithoutContext | gen.WithDefaultQuery | gen.WithQueryInterface, // generate mode
	})

	// gormdb, _ := gorm.Open(mysql.Open("root:@(127.0.0.1:3306)/demo?charset=utf8mb4&parseTime=True&loc=Local"))
	g.UseDB(db) // reuse your gorm db

	// Generate basic type-safe DAO API for struct `model.User` following conventions
	g.ApplyBasic(mysqlmodel.ReviewInfo{}, mysqlmodel.ReviewImage{}, mysqlmodel.ReviewReployInfo{})

	// Generate Type Safe API with Dynamic SQL defined on Querier interface for `model.User` and `model.Company`
	// g.ApplyInterface(func(Querier) {}, model.User{}, model.Company{})

	// Generate the code
	g.Execute()
}

func main() {
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := "root:123456@tcp(127.0.0.1:3306)/review?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	// 自动迁移
	autoMigrae(db)

	// 插入数据
	mysqlquery.SetDefault(db)
	ctx := context.Background()
	reviewDemo := mysqlmodel.ReviewInfo{
		UserID:         8,
		Content:        "外卖口味不错，值得购买",
		ShopID:         13,
		ShopScore:      18,
		LogisticsScore: 66,
		HavePicture:    false,
		Status:         mysqlmodel.ReviewStatusPending,
		OptIdea:        "",
	}

	if err := mysqlquery.ReviewInfo.WithContext(ctx).Create(&reviewDemo); err != nil {
		panic(err)
	}
	// 查询一下数据
	review, err := mysqlquery.ReviewInfo.WithContext(ctx).Where(mysqlquery.ReviewInfo.UserID.Eq(8)).First()
	if err != nil {
		panic(err)
	}
	// 打印一下数据
	fmt.Printf("%+v", review)
}
